package com.hkfn.rfb.rfb.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.hkfn.rfb.R;
import com.hkfn.rfb.common.activity.BaseActivity;
import com.hkfn.rfb.common.bean.BaseModel;
import com.hkfn.rfb.common.bean.chart.ChartModel;
import com.hkfn.rfb.common.bean.chart.LineModel;
import com.hkfn.rfb.common.fragment.BaseFragment;
import com.hkfn.rfb.common.utils.StringUtils;
import com.hkfn.rfb.databinding.FRfbDataMonitorBinding;
import com.hkfn.rfb.rfb.adapter.RfbDataMonitorAdapter;
import com.hkfn.rfb.rfb.bean.RfbDataModel;
import com.hkfn.rfb.rfb.bean.RfbDataMonitorModel;
import com.hkfn.rfb.rfb.bean.RfbParamManager;
import com.hkfn.rfb.rfb.bean.RfbParamModel;
import com.hkfn.rfb.view.TagListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 数据监控
 */
public class RfbDataMonitorFragment extends BaseFragment {

    private BaseActivity activity;

    private Bundle bundle;

    private FRfbDataMonitorBinding fRfbDataMonitorBinding;

    private int currentPage = -1;// 当前选中页面

    private List<RfbParamModel> batterySelectList;
    private List<RfbParamModel> temperatureSelectList;
    private List<RfbParamModel> gasSelectList;

    private RfbDataMonitorAdapter rfbDataMonitorAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = getMyActivity();
        bundle = getArguments();
        fRfbDataMonitorBinding = FRfbDataMonitorBinding.inflate(inflater, container, false);
        initView();
        return fRfbDataMonitorBinding.getRoot();
    }

    private void initView() {

        initHeadTabs();

        initDataFormList();

        initLineSelectItemList();

        initLineChart(fRfbDataMonitorBinding.lcDataMonitor);

        clickHeadTabAction(0);
    }

    private void initHeadTabs() {
        fRfbDataMonitorBinding.tvTabBattery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickHeadTabAction(0);
            }
        });
        fRfbDataMonitorBinding.tvTabTemperature.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickHeadTabAction(1);
            }
        });
        fRfbDataMonitorBinding.tvTabGas.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickHeadTabAction(2);
            }
        });

        fRfbDataMonitorBinding.llChangeChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (fRfbDataMonitorBinding.lcDataMonitor.getVisibility() == View.GONE){
//                    fRfbDataMonitorBinding.lcDataMonitor.setVisibility(View.VISIBLE);
//                    fRfbDataMonitorBinding.tlvSelectDataList.setVisibility(View.VISIBLE);
//                    fRfbDataMonitorBinding.llClearChart.setVisibility(View.VISIBLE);
//                    fRfbDataMonitorBinding.rlvDataMonitor.setVisibility(View.GONE);
//                    fRfbDataMonitorBinding.tvChangeChart.setText("切换表格");
//                }else {
//                    fRfbDataMonitorBinding.lcDataMonitor.setVisibility(View.GONE);
//                    fRfbDataMonitorBinding.tlvSelectDataList.setVisibility(View.GONE);
//                    fRfbDataMonitorBinding.llClearChart.setVisibility(View.GONE);
//                    fRfbDataMonitorBinding.rlvDataMonitor.setVisibility(View.VISIBLE);
//                    fRfbDataMonitorBinding.tvChangeChart.setText("切换图表");
//                }
            }
        });
        fRfbDataMonitorBinding.llClearChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearCurrentSelectItemList();
                setLineSelectItemList();
            }
        });
    }

    private void clickHeadTabAction(int clickIndex){
        if (clickIndex != currentPage){
            // 将当前已选中tabs设为未选中状态
            switch (currentPage){
                case 0:
                    fRfbDataMonitorBinding.tvTabBattery.setBackground(activity.getResources().getDrawable(R.drawable.shape_rfb_head_tab_border_frame));
                    break;
                case 1:
                    fRfbDataMonitorBinding.tvTabTemperature.setBackground(activity.getResources().getDrawable(R.drawable.shape_rfb_head_tab_border_frame));
                    break;
                case 2:
                    fRfbDataMonitorBinding.tvTabGas.setBackground(activity.getResources().getDrawable(R.drawable.shape_rfb_head_tab_border_frame));
                    break;
            }
            currentPage = clickIndex;
            // 将当前点击tabs设为选中状态
            switch (currentPage){
                case 0:
                    fRfbDataMonitorBinding.tvTabBattery.setBackground(activity.getResources().getDrawable(R.drawable.shape_rfb_head_tab_select_frame));
                    break;
                case 1:
                    fRfbDataMonitorBinding.tvTabTemperature.setBackground(activity.getResources().getDrawable(R.drawable.shape_rfb_head_tab_select_frame));
                    break;
                case 2:
                    fRfbDataMonitorBinding.tvTabGas.setBackground(activity.getResources().getDrawable(R.drawable.shape_rfb_head_tab_select_frame));
                    break;
            }
            refreshFormAndLineData();
        }
    }

    /**
     * 刷新列表和折线图数据
     */
    private void refreshFormAndLineData() {
        // 设置表格数据
        setDataFormData();
        // 设置选择列表
        setLineSelectItemList();
    }


    private void initDataFormList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        fRfbDataMonitorBinding.rlvDataMonitor.setLayoutManager(linearLayoutManager);

        rfbDataMonitorAdapter = new RfbDataMonitorAdapter(activity);
        fRfbDataMonitorBinding.rlvDataMonitor.setAdapter(rfbDataMonitorAdapter);
    }

    /**
     * 设置表格数据
     */
    private void setDataFormData() {
        rfbDataMonitorAdapter.clear();
        if (currentPage == 0){
            rfbDataMonitorAdapter.addDatas((List<RfbDataMonitorModel>) getBatteryData(true));
        }else if (currentPage == 1){
            rfbDataMonitorAdapter.addDatas((List<RfbDataMonitorModel>) getTemperatureData(true));
        }else if (currentPage == 2){
            rfbDataMonitorAdapter.addDatas((List<RfbDataMonitorModel>) getGasData(true));
        }
        if (rfbDataMonitorAdapter.getItemCount() > 0) {
            fRfbDataMonitorBinding.rlvDataMonitor.scrollToPosition(0);
        }
    }

    /**
     * 初始化曲线图选项
     */
    private void initLineSelectItemList() {
        batterySelectList = (List<RfbParamModel>) getBatteryData(false);
        temperatureSelectList = (List<RfbParamModel>) getTemperatureData(false);
        gasSelectList = (List<RfbParamModel>) getGasData(false);
        fRfbDataMonitorBinding.tlvSelectDataList.setOnTagClickListener(new TagListView.OnTagClickListener() {
            @Override
            public void onTagClick(LinearLayout tagView, BaseModel tag, int location) {
                changeSelectState(location);
            }
        });
        fRfbDataMonitorBinding.tlvSelectDataList.setOnCheckChangeListener(new TagListView.OnCheckChangeListener() {
            @Override
            public void onCheckChange(boolean isCheck, int location) {
                changeSelectState(location);
            }
        });
    }

    private void changeSelectState(int location){
        if (currentPage == 0){
            batterySelectList.get(location).setSelected(!batterySelectList.get(location).isSelected());
        }else if (currentPage == 1){
            temperatureSelectList.get(location).setSelected(!temperatureSelectList.get(location).isSelected());
        }else if (currentPage == 2){
            gasSelectList.get(location).setSelected(!gasSelectList.get(location).isSelected());
        }
        setLineSelectItemList();
    }

    /**
     * 设置曲线图选项
     */
    private void setLineSelectItemList() {
        if (currentPage == 0){
            fRfbDataMonitorBinding.tlvSelectDataList.setTags(batterySelectList);
        }else if (currentPage == 1){
            fRfbDataMonitorBinding.tlvSelectDataList.setTags(temperatureSelectList);
        }else if (currentPage == 2){
            fRfbDataMonitorBinding.tlvSelectDataList.setTags(gasSelectList);
        }
        setLineChartData(fRfbDataMonitorBinding.lcDataMonitor);
    }

    /**
     * 初始化折线图
     */
    private void initLineChart(LineChart lineChart) {
        // no description text
        lineChart.getDescription().setEnabled(false);

        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(true);

        lineChart.setDrawGridBackground(false);
        lineChart.setMaxHighlightDistance(300);

        lineChart.getAxisRight().setEnabled(false);

        Legend legend = lineChart.getLegend();
        legend.setEnabled(true);
        legend.setTextColor(activity.getResources().getColor(R.color.white));
        legend.setTextSize(15);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setWordWrapEnabled(true);
        legend.setXEntrySpace(30);
        legend.setYEntrySpace(10);


        lineChart.animateXY(0, 800);
        lineChart.setScaleYEnabled(false);


        XAxis x = lineChart.getXAxis();
        x.setTextColor(activity.getResources().getColor(R.color.white));
        x.setEnabled(true);
        x.setDrawGridLines(false);
        x.setPosition(XAxis.XAxisPosition.BOTTOM);
        x.setAxisLineColor(Color.WHITE);
        x.setGranularityEnabled(false);
        x.setGranularity(1);
        x.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return (int)value+"";
            }

        });

        YAxis y = lineChart.getAxisLeft();
        Typeface tfLight = Typeface.DEFAULT;
        y.setTypeface(tfLight);
        y.setTextColor(activity.getResources().getColor(R.color.white));
        y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        y.setDrawGridLines(false);
        y.setAxisLineColor(Color.WHITE);
        y.setGranularityEnabled(false);
        y.setGranularity(1);
    }

    private void setLineChartData(LineChart lineChart){
        ChartModel chartModel = getCurrentChartData();

        XAxis x = lineChart.getXAxis();
        x.setLabelCount(chartModel.getXAxisValues().size());
        //创建一个数据集
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        List<LineModel> lineModels = chartModel.getLineModels();
        int[] colors = activity.getResources().getIntArray(R.array.chart_line_colors);
        for (int i = 0; i < lineModels.size(); i++) {
            ArrayList<Entry> entries = new ArrayList<>();
            for (int j = 0; j < lineModels.get(i).getYAxisValues().size(); j++) {
                entries.add(new Entry(j, lineModels.get(i).getYAxisValues().get(j)));
            }
            int color = colors[i % 16];
            // create a dataset and give it a type
            LineDataSet lineDataSet = new LineDataSet(entries, lineModels.get(i).getLineTitle());
            lineDataSet.setDrawFilled(true);
            lineDataSet.setDrawCircles(false);
            lineDataSet.setDrawValues(false);
            lineDataSet.setCircleHoleColor(color);
            lineDataSet.setLineWidth(2f);
            lineDataSet.setCircleRadius(2f);
            lineDataSet.setCircleColor(color);
            lineDataSet.setColor(color);
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            lineDataSet.setFillDrawable(activity.getResources().getDrawable(R.drawable.shape_chart_line_bg));

            dataSets.add(lineDataSet);
        }

        LineData lineData = new LineData(dataSets);
        //设置数据
        lineChart.setData(lineData);
        lineChart.invalidate();
    }

    private Object getBatteryData(boolean isForm){
        String[] dataNameList = new String[]{"电池正极进口温度", "电池正极出口温度", "电池负极进口温度", "电池负极出口温度",
                "电池正极进口压力", "电池正极进液流量", "电池负极进口压力", "电池负极进液流量",
                "电池巡检电压", "电池开路电压", "正极储罐液位", "负极储罐液位", "正极储罐上部气压", "负极储罐上部气压"};
        String[] dataUnitList = new String[]{"℃", "℃", "℃", "℃",
                "mH2O", "L/min", "mH2O", "L/min",
                "V", "V", "mm", "mm", "mH2O", "mH2O"};
        int[] boundList = new int[]{35, 45, 35, 45, 15, 300, 15, 300, 83, 1, 3, 3, 11, 11};
        if (isForm) {
            return getCurrentFormDataByList(RfbParamManager.batteryParamManager);
        }else {
            return getCurrentSelectListDataByList(RfbParamManager.batteryParamManager);
        }
    }

    private Object getTemperatureData(boolean isForm){
        String[] dataNameList = new String[]{"正极电解液经冷却器进口温度", "正极电解液经冷却器出口温度",
                "正极电解液冷却进口压力", "正极电解液冷却流量",
                "负极电解液经冷却器进口温度", "负极电解液经冷却器出口温度", "负极电解液冷却进口压力", "负极电解液冷却流量",
                "正极冷却器冷却介质进口压力", "正极冷却器冷却介质进口温度", "正极冷却器冷却介质出口温度",
                "正极冷却器冷却介质流量", "负极冷却器冷却介质进口压力",
                "负极冷却器冷却介质进口温度","负极冷却器冷却介质出口温度","负极冷却器冷却介质流量"};
        String[] dataUnitList = new String[]{"℃", "℃", "mH2O", "L/min",
                "℃", "℃", "mH2O", "L/min",
                "mH2O", "℃", "℃", "L/min", "mH2O", "℃", "℃", "L/min"};
        int[] boundList = new int[]{35, 45, 15, 300, 35, 45, 15, 300, 15, 300, 35, 45, 300, 15, 35, 45, 300};
        if (isForm) {
            return getCurrentFormDataByList(RfbParamManager.temperatureParamManager);
        }else {
            return getCurrentSelectListDataByList(RfbParamManager.temperatureParamManager);
        }
    }

    private Object getGasData(boolean isForm){
        String[] dataNameList = new String[]{"电池检漏氮气正极压力", "电池检漏氮气负极压力", "正负极储罐上部气压", "正负极储罐上部氧气浓度"};
        String[] dataUnitList = new String[]{"mH2O", "mH2O", "mH2O", "%"};
        int[] boundList = new int[]{2, 2, 11, 5};
        if (isForm) {
            return getCurrentFormDataByList(RfbParamManager.gasParamManager);
        }else {
            return getCurrentSelectListDataByList(RfbParamManager.gasParamManager);
        }
    }

    private List<RfbDataModel> getCurrentSelectListData(String[] dataNameList, String[] dataUnitList){
        List<RfbDataModel> rfbDataModels = new ArrayList<>();
        for (int i = 0; i < dataNameList.length; i++) {
            RfbDataModel rfbDataModel = new RfbDataModel();
            rfbDataModel.setDataName(dataNameList[i]);
            rfbDataModel.setDataUnit(dataUnitList[i]);
            rfbDataModel.setSelected(false);
            rfbDataModels.add(rfbDataModel);
        }
        return rfbDataModels;
    }

    private List<RfbParamModel> getCurrentSelectListDataByList(List<RfbParamModel> list){
        return list;
    }

    private ChartModel getCurrentChartData(){
        ChartModel chartModel = new ChartModel();
        List<Float> xAxisValues = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            xAxisValues.add((float) (i+1));
        }
        chartModel.setXAxisValues(xAxisValues);

        List<LineModel> lineModels = new ArrayList<>();
        List<RfbParamModel> currentSelectItemList = getCurrentSelectItemList();
        for (int i = 0; i < currentSelectItemList.size(); i++) {
            RfbParamModel rfbParamModel = currentSelectItemList.get(i);
            if (rfbParamModel.isSelected()) {
                LineModel lineModel = new LineModel();
                lineModel.setLineTitle(rfbParamModel.getParamNameAndUnit());
                List<Float> yAxisValues = new ArrayList<>();
                for (int j = 0; j < 10; j++) {
                    yAxisValues.add(Float.parseFloat(rfbParamModel.getParamRandomValue()));
                }
                lineModel.setYAxisValues(yAxisValues);
                lineModels.add(lineModel);
            }
        }
        chartModel.setLineModels(lineModels);
        return chartModel;
    }

    private List<RfbParamModel> getCurrentSelectItemList(){
        List<RfbParamModel> rfbParamModels = new ArrayList<>();
        if (null != batterySelectList) {
            for (RfbParamModel rfbParamModel : batterySelectList) {
                if (rfbParamModel.isSelected()) {
                    rfbParamModels.add(rfbParamModel);
                }
            }
        }
        if (null != temperatureSelectList) {
            for (RfbParamModel rfbParamModel : temperatureSelectList) {
                if (rfbParamModel.isSelected()) {
                    rfbParamModels.add(rfbParamModel);
                }
            }
        }
        if (null != gasSelectList) {
            for (RfbParamModel rfbParamModel : gasSelectList) {
                if (rfbParamModel.isSelected()) {
                    rfbParamModels.add(rfbParamModel);
                }
            }
        }
        return rfbParamModels;
    }

    private void clearCurrentSelectItemList(){
        if (null != batterySelectList) {
            for (RfbParamModel rfbParamModel : batterySelectList) {
                rfbParamModel.setSelected(false);
            }
        }
        if (null != temperatureSelectList) {
            for (RfbParamModel rfbParamModel : temperatureSelectList) {
                rfbParamModel.setSelected(false);
            }
        }
        if (null != gasSelectList) {
            for (RfbParamModel rfbParamModel : gasSelectList) {
                rfbParamModel.setSelected(false);
            }
        }
    }

    private List<RfbDataMonitorModel> getCurrentFormData(String[] dataNameList, String[] dataUnitList, int[] boundList){
        List<List<RfbDataModel>> batteryDataList = new ArrayList<>();
        for (int i = 0; i < dataNameList.length; i++) {
            List<RfbDataModel> list = new ArrayList<>();
            batteryDataList.add(list);
        }

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < dataNameList.length; j++) {
                batteryDataList.get(j).add(getDataModel(dataNameList[j], boundList[j], dataUnitList[j]));
            }
        }

        List<RfbDataMonitorModel> formList = new ArrayList<>();
        List<RfbDataModel> nameList = new ArrayList<>();
        nameList.add(new RfbDataModel("", "数据名称", ""));
        for (int i = 0; i < dataNameList.length; i++) {
            nameList.add(new RfbDataModel("", dataNameList[i] + "(" + dataUnitList[i] + ")", ""));
        }
        formList.add(new RfbDataMonitorModel(nameList));
        for (int i = 0; i < 10; i++) {
            List<RfbDataModel> dataList = new ArrayList<>();
            dataList.add(new RfbDataModel("", ""+(i+1), ""));
            for (int j = 0; j < dataNameList.length; j++) {
                dataList.add(batteryDataList.get(j).get(i));
            }
            formList.add(new RfbDataMonitorModel(dataList));
        }
        return formList;
    }

    private List<RfbDataMonitorModel> getCurrentFormDataByList(List<RfbParamModel> list){
        List<List<RfbDataModel>> batteryDataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<RfbDataModel> rfbDataModels = new ArrayList<>();
            batteryDataList.add(rfbDataModels);
        }

        for (int i = 0; i < 10; i++) {
            double entraPress1 = 0;
            double entraPress2 = 0;
            double entraAirPress1 = 0;
            double entraAirPress2 = 0;
            for (int j = 0; j < list.size(); j++) {
                RfbParamModel rfbParamModel = list.get(j);
                String value = rfbParamModel.getParamRandomValue();
                if (!StringUtils.isEmpty(rfbParamModel.getIntervalValueStr()) || rfbParamModel.getParamName().equals("充电功率")){
                    value = rfbParamModel.getParamRandomValue(i);
                }
                if (rfbParamModel.getParamName().equals("正极电解液进口压力")){
                    entraPress1 = Double.parseDouble(value);
                }else if (rfbParamModel.getParamName().equals("负极电解液进口压力")){
                    entraPress2 = Double.parseDouble(value);
                }else if (rfbParamModel.getParamName().equals("正负极电解液进口压力差")){
                    value = String.format("%.3f", entraPress1 - entraPress2);
                }else if (rfbParamModel.getParamName().equals("正极储罐上部气压")){
                    entraAirPress1 = Double.parseDouble(value);
                }else if (rfbParamModel.getParamName().equals("负极储罐上部气压")){
                    entraAirPress2 = Double.parseDouble(value);
                }else if (rfbParamModel.getParamName().equals("正负极储罐上部气压差")){
                    value = String.format("%.3f", entraAirPress1 - entraAirPress2);
                }
                batteryDataList.get(j).add(new RfbDataModel(rfbParamModel.getParamName(), value, rfbParamModel.getParamUnit()));
            }
        }

        List<RfbDataMonitorModel> formList = new ArrayList<>();
        List<RfbDataModel> nameList = new ArrayList<>();
        nameList.add(new RfbDataModel("", "数据名称", ""));
        for (int i = 0; i < list.size(); i++) {
            nameList.add(new RfbDataModel("", list.get(i).getParamNameAndUnit(), ""));
        }
        formList.add(new RfbDataMonitorModel(nameList));
        for (int i = 0; i < 10; i++) {
            List<RfbDataModel> dataList = new ArrayList<>();
            dataList.add(new RfbDataModel("", ""+(i+1), ""));
            for (int j = 0; j < list.size(); j++) {
                dataList.add(batteryDataList.get(j).get(i));
            }
            formList.add(new RfbDataMonitorModel(dataList));
        }
        return formList;
    }


    private RfbDataModel getDataModel(String name,  int bound, String unit){
        Random random = new Random();
        return new RfbDataModel(name, String.format("%.3f", random.nextFloat() * bound), unit);
    }
}
